package cn.hsa.fqz.ftp;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class FtpUploader {

    private FtpConfig config;

    public final static String SEPRATOR = "/";


    public FtpUploader(FtpConfig config) {
        this.config = config;
    }

    public boolean uploadFile(InputStream localFileStream, String remoteDirectory,String remoteFileName) throws Exception {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(config.getHost(), config.getPort());
            ftpClient.login(config.getUsername(), config.getPassword());
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);


            if (ftpClient.isConnected()) {
                if (!ftpClient.changeWorkingDirectory(remoteDirectory)) {
                    if (ftpClient.makeDirectory(remoteDirectory)) {
                        ftpClient.changeWorkingDirectory(remoteDirectory);
                    }
                }
                String ftpFileName = new String(remoteFileName.getBytes(), StandardCharsets.ISO_8859_1);
                boolean success = ftpClient.storeFile(ftpFileName, localFileStream);
                return success;
            }
        } finally {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        }
        return false;
    }

    public FTPFile[] listFiles(String remoteDirectory) throws Exception {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(config.getHost(), config.getPort());
            ftpClient.login(config.getUsername(), config.getPassword());
            ftpClient.enterLocalPassiveMode();

            if (ftpClient.isConnected()) {
                return ftpClient.listFiles(remoteDirectory);
            }
        } finally {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        }
        return null;
    }

/*    public static void main(String[] args) throws Exception {
        FtpConfig config = new FtpConfig("localhost",21,"zmjk","zmjk2018");
        FtpUploader uploader = new FtpUploader(config);
        FileInputStream f = new FileInputStream("D:\\damon.json");
        uploader.uploadFile(f,"xx/bb","damon-new01.json");
    }*/
}
